package com.wf.smartcomm.server.admin.action;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.aspectj.util.FileUtil;
import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.druid.util.StringUtils;
import com.cloopen.rest.sdk.CCPRestSDK;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.apns.IApnsService;
import com.wf.smartcomm.server.apns.model.Payload;
import com.wf.smartcomm.server.bean.Bill;
import com.wf.smartcomm.server.bean.House;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.service.BillService;
import com.wf.smartcomm.server.service.HouseService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.service.VillageService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.ObjectExcelRead;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.util.StringUtil;

/** 
 * @author 38884306@qq.com  
 * @version 创建时间：2015-6-3 下午4:13:32 
 * 
 */
@Controller(value="adminHouseAction")
@Scope("prototype")
public class HouseAction extends BaseAction implements ModelDriven<House> {
	
	private House house = new House();
	@Resource
	private HouseService houseServiceImpl;
	@Resource
	private UnitMachService umServiceImpl;
	@Resource
	private VillageService villageServiceImpl;
	@Resource
	private BillService billService;
	@Resource
	private UserService userServiceImpl;
	
	private List<File> upload;  
    // /多个上传文件的类型集合  
    private List<String> uploadContentType;  
   // 多个上传文件的文件名集合  
    private List<String> uploadFileName;
    
	public House getHouse() {
		return house;
	}

	public void setHouse(House house) {
		this.house = house;
	}

	public HouseService getHouseServiceImpl() {
		return houseServiceImpl;
	}

	public void setHouseServiceImpl(HouseService houseServiceImpl) {
		this.houseServiceImpl = houseServiceImpl;
	}

	public UnitMachService getUmServiceImpl() {
		return umServiceImpl;
	}

	public void setUmServiceImpl(UnitMachService umServiceImpl) {
		this.umServiceImpl = umServiceImpl;
	}

	public List<File> getUpload() {
		return upload;
	}

	public void setUpload(List<File> upload) {
		this.upload = upload;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void add() throws Exception{
		
		if (!StringUtil.isEmpty(house.getObjectId())) {
			House sourceHouse = houseServiceImpl.getById(house.getObjectId());
			sourceHouse.setDisAddress(house.getRegion()+house.getBuilding()+"栋"+house.getEntrance()+"单元"+house.getNumber()+"室");
			sourceHouse.update(house);
			sourceHouse.setId(IdUtils.MD5(sourceHouse.getId()));
			houseServiceImpl.update(sourceHouse);
			printJsonData(200);
			return;
		}
		User user = (User) session.getAttribute("loginUser");
		Village village = villageServiceImpl.get(user.getLoginVillage().getObjectId());
		Bill bill = new Bill();
		try {
			Long getAt = Long.parseLong(house.getGetAt());
			BigDecimal sum = house.getPrice().multiply(new BigDecimal(house.getArea())).multiply(new BigDecimal(village.getPeriod()));
			bill.setPrice(sum);
			bill.setHouse(house);
			bill.setOrderCode("WY"+System.currentTimeMillis()+new Random().nextInt(999));
			GregorianCalendar gc =new GregorianCalendar();
			gc.setTimeInMillis(getAt);
			gc.add(GregorianCalendar.MONTH, village.getPeriod());
			house.setNotifyDate(String.valueOf(gc.getTimeInMillis()));
			bill.setFromAt(house.getGetAt());
			bill.setToAt(house.getNotifyDate());
			bill.setStatus(ConstantUtils.BILL_STATUS_CREATED);
			bill.setType(ConstantUtils.BILL_TYPE_UNLOCKED);
		} catch (Exception e) {
			e.printStackTrace();
		}
		house.setVillage(user.getLoginVillage());
		house.setDisAddress(house.getRegion()+house.getBuilding()+"栋"+house.getEntrance()+"单元"+house.getNumber()+"室");
		houseServiceImpl.save(house);
		billService.add(bill);
		User exist = userServiceImpl.getUserByUsername(house.getPhoneNumber());
		if (exist == null) {
			exist = new User();
			exist.setUsername(house.getPhoneNumber());
			exist.setPassword(IdUtils.MD5("123456"));
			exist.setUserType(ConstantUtils.USER_TYPE_APP);
			exist.setObjectId(IdUtils.uuid());
			exist.setPushId(IdUtils.uuid16());
			exist.setName(house.getName());
			exist.setCreatedAt(String.valueOf(System.currentTimeMillis()));
			exist.setUpdateAt(exist.getCreatedAt());
			exist.setIsUnReg("0");
			exist.setDeviceType(ConstantUtils.DEVICE_TYPE_UNKNOW);
			exist.setType(ConstantUtils.USER_TYPE_PRIMARY);
			exist.setLoginVillage(house.getVillage());
			HashMap<String, Object> result = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			if (PushUtils.isDevEnv) {
				restAPI.init("sandboxapp.cloopen.com", "8883");
				restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
				restAPI.setAppId("aaf98f89516bf50b015180a2d42a2875");
			} else {
				restAPI.init(PushUtils.pushConfig.getProperty("CloudAddress"), PushUtils.pushConfig.getProperty("CloudPort"));// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
				restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));// 初始化主帐号和主帐号TOKEN
				restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));// 初始化应用ID
			}
			result = restAPI.createSubAccount(exist.getObjectId());
			if("000000".equals(result.get("statusCode"))){
				//正常返回输出data包体信息（map）
				HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
				List<HashMap<String,Object>> object =  (List<HashMap<String,Object>>) data.get("SubAccount");
				for (HashMap<String, Object> hashMap : object) {
					if (hashMap.containsKey("subAccountSid")) {
						exist.setSubAccountSid(hashMap.get("subAccountSid").toString());
					}
					if (hashMap.containsKey("voipAccount")) {
						exist.setVoipAccount(hashMap.get("voipAccount").toString());
					}
					if (hashMap.containsKey("voipPwd")) {
						exist.setVoipPwd(hashMap.get("voipPwd").toString());
					}
					if (hashMap.containsKey("subToken")) {
						exist.setSubToken(hashMap.get("subToken").toString());
					}
				}
				userServiceImpl.registe(exist);
			}
		}
		house.setUser(exist);
		houseServiceImpl.update(house);
		houseServiceImpl.addUser(house.getObjectId(), exist.getObjectId());
		umServiceImpl.listByAddress(house.getVillage().getObjectId(),house.getRegion(),house.getBuilding(),house.getEntrance(),page);
		List<UnitMachine> ums = (List<UnitMachine>) page.getDataList();
		List<House> houses = new ArrayList<House>();
		houses.add(house);
		for (UnitMachine um : ums) {
			umServiceImpl.saveHouseRelation(um, houses);
		}
		pushMsgToUnitMachine(umServiceImpl.listCenterMachine());
		printJsonData(200);
	}
	
	public void list() throws Exception {
		
		String hostId = request.getParameter("hostId");
		String attachId = request.getParameter("attachId");
		User user = (User) session.getAttribute("loginUser");
		if (!StringUtil.isEmpty(hostId)) {
			houseServiceImpl.listByHost(hostId, page);
			HashMap<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("iTotalRecords", page.getTotalCount());
			dataMap.put("sEcho",1);
			dataMap.put("iTotalDisplayRecords", page.getTotalCount());
			dataMap.put("aaData", page.getDataList());
			printJsonData(outGson.toJson(dataMap));
			return;
		}
		
		if (!StringUtil.isEmpty(attachId)) {
			houseServiceImpl.listByAttach(attachId, page);
			HashMap<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("iTotalRecords", page.getTotalCount());
			dataMap.put("sEcho",1);
			dataMap.put("iTotalDisplayRecords", page.getTotalCount());
			dataMap.put("aaData", page.getDataList());
			printJsonData(outGson.toJson(dataMap));
			return;
		}
		
		String aoData = request.getParameter("aoData");
		//System.out.println("aodata:"+aoData);
		String sEcho = "";
		String iDisplayStart = "";
		String iDisplayLength = "";
		String sSearch = "";
		JSONObject jo = new JSONObject(aoData);
		sEcho = jo.getString("sEcho");
		iDisplayStart = jo.getString("iDisplayStart");
		iDisplayLength = jo.getString("iDisplayLength");
		sSearch = jo.getString("sSearch");
		
		page.setBeginIndex(Integer.parseInt(iDisplayStart));
		page.setPageSize(Integer.parseInt(iDisplayLength));
		if (!StringUtil.isEmpty(sSearch)) {
			houseServiceImpl.queryByKey(user.getLoginVillage(),sSearch, page);
		}else {
			houseServiceImpl.listByVillage(user.getLoginVillage(),page);
		}
		
		int  initEcho = Integer.parseInt(sEcho)+1;
		int count = page.getTotalCount();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("iTotalRecords", count);
		dataMap.put("sEcho",initEcho);
		dataMap.put("iTotalDisplayRecords", count);
		dataMap.put("aaData", page.getDataList());
		printJsonData(outGson.toJson(dataMap));
	}
	
	private void pushMsgToUnitMachine(List<UnitMachine> ums) throws Exception{
		Pusher pusher = PushUtils.getInstance();
		PushMessage msg = new PushMessage();
		msg.setPushType(ConstantUtils.PUSH_TYPE_INFO_UPDATE);
		for (UnitMachine unitMachine : ums) {
			pusher.push0x20Message(unitMachine.getPushId().getBytes(), outGson.toJson(msg).getBytes());
		}
		pusher.close();
	}
	
	public String readExcel() throws Exception{
		if (upload != null && upload.size() > 0) {
			File attachFile = upload.get(0);
			String fileName = uploadFileName.get(0);
			String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			String path = request.getServletContext().getRealPath("excels")+File.separator+datePath;
			String fullPath = path+File.separator+fileName;
			File des = new File(fullPath);
			FileUtil.copyFile(attachFile, des);
			List<HashMap<String,String>> list = ObjectExcelRead.readExcel(path, fileName, 2, 0, 0);
			//HashMap<String,String> map = new HashMap<String,String>();
			/**
			 * var0 :小区名称
			 * var1 :区/期
			 * var2 :楼栋号
			 * var3 :单元号
			 * var4 :房号
			 * var5 :业主姓名
			 * var6 :业主身份证
			 * var7 :业主电话
			 * var8 :房间面积
			 * var9 :购房日期
			 * var10 :收房日期
			 * var11 :物业费单价
			 */
			if (list.size() > 0) {
				String villageName = list.get(0).get("var0");
				Village village = villageServiceImpl.getByName(villageName);
				if (village != null) {
					 for (HashMap<String, String> houseMap : list) {
							String region = houseMap.get("var1");
							String building = houseMap.get("var2");
							String entrance = houseMap.get("var3");
							String number = houseMap.get("var4");
							String name = houseMap.get("var5");
							//String id = houseMap.get("var6");
							String phone = houseMap.get("var7");
							String area = houseMap.get("var8");
							String buyDate = houseMap.get("var9");
							String getDate = houseMap.get("var10");
							String price = houseMap.get("var11");
							House house = new House();
							house.setRegion(region);
							if (!StringUtils.isEmpty(area)) {
								house.setArea(area);
							}
							house.setBuilding(building);
							if (!StringUtils.isEmpty(buyDate) && !buyDate.contains("-")) {
								house.setBuyAt(buyDate);
							}
							
							house.setDisAddress(villageName + region +"区" + building +"栋"+ entrance+"单元" + number+"室");
							house.setEntrance(entrance);
							if (!StringUtils.isEmpty(getDate) && !getDate.contains("-")) {
								house.setGetAt(getDate);
							}
							//house.setId(IdUtils.MD5(id));
							house.setName(name);
							house.setNumber(number);
							if (!StringUtils.isEmpty(phone)) {
								house.setPhoneNumber(phone);
								house.setVoipPhoneNumber(phone);
							}
							if (!StringUtils.isEmpty(price)) {
								house.setPrice(new BigDecimal(price));
							}
							house.setVillage(village);
							Bill bill = null;
							if (!StringUtils.isEmpty(house.getGetAt()) && !StringUtils.isEmpty(house.getArea()) && house.getPrice() != null) {
								bill = new Bill();
								Long getAt = Long.parseLong(house.getGetAt());
								BigDecimal sum = house.getPrice().multiply(new BigDecimal(house.getArea())).multiply(new BigDecimal(village.getPeriod()));
								bill.setPrice(sum);
								bill.setHouse(house);
								bill.setOrderCode("WY"+System.currentTimeMillis()+new Random().nextInt(999));
								GregorianCalendar gc =new GregorianCalendar();
								gc.setTimeInMillis(getAt);
								gc.add(GregorianCalendar.MONTH, village.getPeriod());
								house.setNotifyDate(String.valueOf(gc.getTimeInMillis()));
								bill.setFromAt(house.getGetAt());
								bill.setToAt(house.getNotifyDate());
								bill.setStatus(ConstantUtils.BILL_STATUS_CREATED);
								bill.setType(ConstantUtils.BILL_TYPE_UNLOCKED);
							}
							houseServiceImpl.save(house);
							if (bill != null) {
								billService.add(bill);
							}
							User exist = userServiceImpl.getUserByUsername(house.getPhoneNumber());
							if (exist == null) {
								exist = new User();
								exist.setUsername(house.getPhoneNumber());
								exist.setPassword(IdUtils.MD5("123456"));
								exist.setUserType(ConstantUtils.USER_TYPE_APP);
								exist.setObjectId(IdUtils.uuid());
								exist.setPushId(IdUtils.uuid16());
								exist.setCreatedAt(String.valueOf(System.currentTimeMillis()));
								exist.setUpdateAt(exist.getCreatedAt());
								exist.setIsUnReg("0");
								exist.setDeviceType(ConstantUtils.DEVICE_TYPE_UNKNOW);
								exist.setType(ConstantUtils.USER_TYPE_PRIMARY);
								exist.setLoginVillage(house.getVillage());
								exist.setName(house.getName());
								HashMap<String, Object> result = null;
								CCPRestSDK restAPI = new CCPRestSDK();
								if (PushUtils.isDevEnv) {
									restAPI.init("sandboxapp.cloopen.com", "8883");
									restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
									restAPI.setAppId("aaf98f89516bf50b015180a2d42a2875");
								} else {
									restAPI.init(PushUtils.pushConfig.getProperty("CloudAddress"), PushUtils.pushConfig.getProperty("CloudPort"));// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
									restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));// 初始化主帐号和主帐号TOKEN
									restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));// 初始化应用ID
								}
								result = restAPI.createSubAccount(exist.getObjectId());
								if("000000".equals(result.get("statusCode"))){
									//正常返回输出data包体信息（map）
									HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
									List<HashMap<String,Object>> object =  (List<HashMap<String,Object>>) data.get("SubAccount");
									for (HashMap<String, Object> hashMap : object) {
										if (hashMap.containsKey("subAccountSid")) {
											exist.setSubAccountSid(hashMap.get("subAccountSid").toString());
										}
										if (hashMap.containsKey("voipAccount")) {
											exist.setVoipAccount(hashMap.get("voipAccount").toString());
										}
										if (hashMap.containsKey("voipPwd")) {
											exist.setVoipPwd(hashMap.get("voipPwd").toString());
										}
										if (hashMap.containsKey("subToken")) {
											exist.setSubToken(hashMap.get("subToken").toString());
										}
									}
									userServiceImpl.registe(exist);
								}
							}
							house.setUser(exist);
							houseServiceImpl.update(house);
							houseServiceImpl.addUser(house.getObjectId(), exist.getObjectId());
							umServiceImpl.listByAddress(village.getObjectId(),region,building,entrance,page);
							List<UnitMachine> ums = (List<UnitMachine>) page.getDataList();
							List<House> houses = new ArrayList<House>();
							houses.add(house);
							for (UnitMachine um : ums) {
								umServiceImpl.saveHouseRelation(um, houses);
							}
						}
				}
			}
		}
		pushMsgToUnitMachine(umServiceImpl.listCenterMachine());
		return "list";
	}

	@Override
	public House getModel() {
		// TODO Auto-generated method stub
		return house;
	}
}
